<template>
    <div class="search-suggestion">
      <van-cell  v-for="(item,index) in suggestions"
      :key="index"
        icon="search" @click="$emit('search' , item )">
       <div slot="title" v-if="item" v-html="highlight(item,searchText)"></div>
    </van-cell>
    </div>
  </template>

<script>
import { getSearchSuggestions } from '@/api/search'
import { debounce, compact } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: []
    }
  },
  computed: {},
  watch: {
    searchText: {
      immediate: true,
      handler: debounce(function (q) {
        this.getSuggestion(q)
      }, 1000)
    }

  },
  created () {},
  mounted () {},
  methods: {
    highlight (source, keyword) {
      if (!source || !keyword) {
        return source
      }
      const reg = new RegExp(keyword, 'gi')
      return source.replace(reg, `<span style="color: #3296fa">${keyword}</span>`)
    },

    async getSuggestion (q) {
      try {
        const { data } = await getSearchSuggestions(q)
        this.suggestions = data.data.options
        this.suggestions = compact(this.suggestions)
      } catch (err) {
        window.console.log(err)
        this.$toast('获取建议失败，请重试')
      }
    }
  }
}
</script>

  <style scoped lang="less"></style>
